package net.ib.mtalk.account;

import net.ib.mtalk.R;
import net.ib.mtalk.constant.MTalkConstant;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class AuthenticatorActivity extends AccountAuthenticatorActivity{
	
	public static final String PARAM_CONFIRMCREDENTIALS 	= "confirmCredentials";
    public static final String PARAM_PASSWORD 				= "password";
    public static final String PARAM_USERNAME 				= "username";
	public static final String PARAM_AUTHTOKEN_TYPE			= "authtokenType";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		
		LoginTask t = new LoginTask(AuthenticatorActivity.this);
		t.execute(GlobalPreferences.getMSISDN());
		
	}
	
	private class LoginTask extends AsyncTask<String, Void, Boolean> {
		Context mContext;
		ProgressDialog mDialog;
		
		LoginTask(Context c) {
			mContext = c;
			
			mDialog = ProgressDialog.show(c, "", getString(R.string.authenticating), true, false);
			mDialog.setCancelable(true);
		}
		
		@Override
		public Boolean doInBackground(String... params) {
			String user = params[0];
			
			// Do something internetty
			try {
				Thread.sleep(2000);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			Bundle result = null;
			Account account = new Account(user, MTalkConstant.ACCOUNT_TYPE);
			AccountManager am = AccountManager.get(mContext);
			if (am.addAccountExplicitly(account, GpbSupport.UuidMsgToString(GlobalPreferences.getUserUUID()), null)) {
				result = new Bundle();
				Log.i("MTalk", account.name +"     13123");
				result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
				result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
				setAccountAuthenticatorResult(result);
				return true;
			} else {
				return false;
			}
		}
		
		@Override
		public void onPostExecute(Boolean result) {
			mDialog.dismiss();
			if (result)
				finish();
		}
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();
		
	}
}
